import type { ConfigEnv, UserConfig } from 'vite';
import { loadEnv } from 'vite';
import { defineConfig } from 'vite';
import { resolve } from 'path';

import { createPlugins } from './build/plugins';
import { include, exclude } from './build/optimize';
import postcssOptions from './build/postcss';

// https://vitejs.dev/config/
export default defineConfig(({ command, mode }: ConfigEnv): UserConfig => {
  const { VITE_BASE_URL, VITE_API_URL_PREFIX, VITE_API_URL } = loadEnv(mode, process.cwd());
  const env = loadEnv(mode, process.cwd());

  console.log('env', env, mode, command);

  return {
    base: VITE_BASE_URL,
    plugins: createPlugins(''),

    resolve: {
      alias: {
        '@': resolve(__dirname, './src'),
        '@store': resolve(__dirname, './src/store'),
        '@api': resolve(__dirname, './src/api'),
        '@router': resolve(__dirname, './src/router'),
      },
    },

    css: {
      postcss: postcssOptions,
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${resolve(__dirname, 'src/assets/style/variables.less')}";`,
          },
          math: 'strict',
          javascriptEnabled: true,
        },
        // scss: {
        //   modifyVars: {
        //     hack: `true; @import (reference) "${resolve(__dirname, 'src/assets/style/variables.scss')}";`,
        //   },
        //   math: 'strict',
        //   javascriptEnabled: true,
        // },
      },
    },

    server: {
      open: true,
      host: '0.0.0.0',
      port: Number(env.VITE_PORT),
      proxy: {
        [VITE_API_URL_PREFIX]: {
          target: VITE_API_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(new RegExp(`^${VITE_API_URL_PREFIX}`), ''),
        },
      },
    },

    optimizeDeps: {
      include,
      exclude,
    },

    build: {
      rollupOptions: {},
    },

    esbuild: {
      // drop: ['console', 'debugger'],
    },
  };
});
